/**
 * src:输入路径
 * dest:输出路径
 * series:同步执行任务
 * parallel:异步执行任务
 */
let { src, dest, series, parallel, watch } = require('gulp');
let gulpClean = require('gulp-clean');
let gulpLess = require('gulp-less');

/**
 * 两个方式任选一个就行,直接在参数里配置会有warning
 *  file: package.json

    "browserslist": [
        "last 2 version",
        "> 5%",
        "IE 10"
      ]
    * file: .browserslistrc
    # Browsers that we support

    last 2 version
    > 5%
    IE 10
 */
let gulpAutoprefixer = require('gulp-autoprefixer');

/**
 * es6 -> es5
 * 该插件依赖 @babel/core,@babel/preset-env 两个依赖
 */
let jsBabel = require('gulp-babel');

let browserify = require('gulp-browserify'); // 将编译后的代码,转成可以在浏览器环境运行的代码

/**
 * 本地开发环境
 */
let webServer = require('gulp-webServer');

/**
 * 文件引入
 */
let fileInclude = require("gulp-file-include");

/**
 * 处理html
 */
const html = () => {
  return src('./src/pages/*.html').pipe(fileInclude()).pipe(dest('./dist/pages/'))
}
/**
 * 处理less
 */
const less = () => {
  return src('./src/assets/less/*.less').pipe(gulpLess()).pipe(gulpAutoprefixer()).pipe(dest('./dist/css/'))
}
/**
 * 处理js,es6转es5
 * browserify 方式 --- 将使用的js打包成浏览器可以运行的文件
 *   不推荐;
 */


const js = () => {
  return src('./src/js/**/*.js').pipe(jsBabel({
    presets:['@babel/preset-env']
  })).pipe(browserify()).pipe(jsBabel()).pipe(dest('./dist/js/'));
}


/**
 * 其他静态资源打包
 */
const static = () => {
  return src('./src/assets/**/*').pipe(dest('./dist/assets/'))
}

/**
 * 删除打包的文件夹
 */
const clean = () => {
  return src('./dist').pipe(gulpClean())
}

/**
 * 跑一个开发环境
 */
const dev = () => {
  return src('./dist').pipe(webServer({
    host: '0.0.0.0',
    port: 4000,
    open: '/pages/index.html',
    livereload: true,
    proxies: []
  }))
}

/**
 * 文件发生变化时,从新更新文件
 */
const listen = () => {
  watch('./src/**/*', parallel(html, static, less, js))
}

/**
 * module.exports 导出的是控制台的手动任务,例:gulp clean
 */
module.exports.clean = clean;
module.exports.html = html;
module.exports.static = static;
module.exports.less = less;
module.exports.js = js;
module.exports.dev = dev;

/**
 * gulp会默认执行gulp default
 */
module.exports.default = series(
  clean,
  parallel(html, static, less, js),
  dev,
  listen
)